package com.lsh.payment.core.strategy.query;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.strategy.config.MisPayConfig;
import com.lsh.payment.core.strategy.vo.mispurse.MisPurseQueryResponse;
import com.lsh.payment.core.util.HttpClientUtils;
import com.lsh.payment.core.util.pay.wxpay.WxSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 16/11/6
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Component
public class MisPurseQueryStrategy implements QueryStrategy<MisPurseQueryResponse> {

    private static final String PAYMENT_QUERY_API = "/trade/info/notify";

    private Logger logger = LoggerFactory.getLogger(MisPurseQueryStrategy.class);

    @Override
    public int getStrategyNo() {
        return BusinessConstant.MIS_QUERY_PAY;
    }

    /**
     * 查询第三方支付状态
     *
     * @param paramMap 查询参数
     * @return
     */
    @Override
    public MisPurseQueryResponse queryPayStatusByParams(Map<String, Object> paramMap) {

        logger.info("查询mis 支付结果:" + JSON.toJSONString(paramMap));
        Map<String, Object> misQueryBody = new HashMap<>(8);
        misQueryBody.put("trade_id", paramMap.get("trade_id").toString());
        misQueryBody.put("appid", MisPayConfig.APPID);

        int timestamp = (int) (System.currentTimeMillis() / 1000);

        String sign = WxSignature.getMisSign(misQueryBody, MisPayConfig.APPID, timestamp);
        Map<String, String> headMap = new HashMap<>();

        headMap.put("timestamp", timestamp + "");
        headMap.put("accesskey", MisPayConfig.APPID);
        headMap.put("sign", sign);
        logger.info("mis下单参数 {}", JSON.toJSONString(misQueryBody));

        String queryResultStr = HttpClientUtils.doPost(MisPayConfig.PAY_API + PAYMENT_QUERY_API, misQueryBody, headMap);

        return this.buildRsp(queryResultStr);
    }

    /**
     * @param queryResultStr
     * @return
     */
    private MisPurseQueryResponse buildRsp(String queryResultStr) {
        MisPurseQueryResponse misPurseQueryResponse = new MisPurseQueryResponse();
        misPurseQueryResponse.setCode(BusinessConstant.PAY_REQUEST_FAIL);
        misPurseQueryResponse.setSuccessFlag(false);
        misPurseQueryResponse.setMsg("mis通信失败");

        JSONObject misQueryResult = JSON.parseObject(queryResultStr);
        //校验返回参数
        if ("0".equals(misQueryResult.getString("ret")) && true == misQueryResult.getBoolean("content")) {

            misPurseQueryResponse.setCode(BusinessConstant.PAY_REQUEST_SUCCESS);
            misPurseQueryResponse.setMsg("签名校验或通信成功");
            misPurseQueryResponse.setSuccessFlag(true);
        } else {
            logger.info("返回查询数据有误");
        }

        return misPurseQueryResponse;
    }

}
